{% extends "base.html" %}

{% block title %}账号管理 - 梦幻西游数字资产管理系统{% endblock %}

{% block mobile_title %}账号管理{% endblock %}

{% block content %}
<div class="container">
    <div class="row mb-4">
        <div class="col-md-6">
            <h2>👤 账号管理</h2>
        </div>
        <div class="col-md-6 text-md-end">
            <div class="btn-group-mobile account-action-buttons">
                <button class="btn btn-secondary action-btn" onclick="resetOrder()">
                    <i class="bi bi-arrow-repeat me-1"></i>重置排序
                </button>
                <button class="btn btn-info action-btn" onclick="downloadTemplate()">
                    <i class="bi bi-download me-1"></i>下载模板
                </button>
                <button class="btn btn-warning action-btn" onclick="$('#importFileInput').click()">
                    <i class="bi bi-file-earmark-arrow-up me-1"></i>导入Excel
                </button>
                <button class="btn btn-success action-btn" onclick="exportToExcel()">
                    <i class="bi bi-file-earmark-excel me-1"></i>导出Excel
                </button>
                <button class="btn btn-primary action-btn" data-bs-toggle="modal" data-bs-target="#addAccountModal">
                    <i class="bi bi-plus-circle me-1"></i>添加账号
                </button>
            </div>
            <input type="file" id="importFileInput" accept=".xlsx,.xls" style="display:none" onchange="handleFileImport(event)">
        </div>
    </div>
    
    <!-- 高级查询 -->
    <div class="card mb-4">
        <div class="card-header">
            <h6 class="mb-0">
                <i class="bi bi-funnel me-2"></i>高级查询
                <button class="btn btn-sm btn-link float-end" type="button" data-bs-toggle="collapse" data-bs-target="#advancedSearch">
                    <i class="bi bi-chevron-down"></i>
                </button>
            </h6>
        </div>
        <div class="card-body collapse show" id="advancedSearch">
            <div class="row g-3">
                <div class="col-md-3">
                    <label class="form-label small">账号名</label>
                    <input type="text" class="form-control" id="searchAccount" placeholder="搜索账号名...">
                </div>
                <div class="col-md-3">
                    <label class="form-label small">密码</label>
                    <input type="text" class="form-control" id="searchPassword" placeholder="搜索密码...">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">账号类型</label>
                    <select class="form-select" id="filterType">
                        <option value="">全部类型</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small">密保类型</label>
                    <select class="form-select" id="filterPasswordType">
                        <option value="">全部密保</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small">状态</label>
                    <select class="form-select" id="filterStatus">
                        <option value="">全部状态</option>
                    </select>
                </div>
            </div>
            <div class="row g-3 mt-2">
                <div class="col-md-2">
                    <label class="form-label small">顺序（最小）</label>
                    <input type="number" class="form-control" id="searchOrderMin" placeholder="最小值">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">顺序（最大）</label>
                    <input type="number" class="form-control" id="searchOrderMax" placeholder="最大值">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">角色数（最小）</label>
                    <input type="number" class="form-control" id="searchRoleCountMin" placeholder="最小值">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">角色数（最大）</label>
                    <input type="number" class="form-control" id="searchRoleCountMax" placeholder="最大值">
                </div>
                <div class="col-md-4">
                    <label class="form-label small">备注</label>
                    <input type="text" class="form-control" id="searchRemarks" placeholder="搜索备注内容...">
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-12 text-end">
                    <button class="btn btn-outline-secondary me-2" onclick="resetSearch()">
                        <i class="bi bi-x-circle me-1"></i>重置
                    </button>
                    <button class="btn btn-primary" onclick="loadAccounts()">
                        <i class="bi bi-search me-1"></i>查询
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 账号列表 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th onclick="sortTable('order')" style="cursor:pointer;">
                                顺序 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th onclick="sortTable('account')" style="cursor:pointer;">
                                账号 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th>密码</th>
                            <th class="d-none d-md-table-cell" onclick="sortTable('account_type')" style="cursor:pointer;">
                                类型 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th class="d-none d-lg-table-cell">密保类型</th>
                            <th onclick="sortTable('status')" style="cursor:pointer;">
                                状态 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th class="d-none d-lg-table-cell">点卡到期</th>
                            <th onclick="sortTable('role_count')" style="cursor:pointer;">
                                角色数 <i class="bi bi-arrow-down-up"></i>
                            </th>
                            <th class="d-none d-xl-table-cell">备注</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="accountTableBody">
                        <tr>
                            <td colspan="10" class="text-center">
                                <div class="spinner-border text-primary my-3" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑账号模态框 -->
<div class="modal fade" id="addAccountModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">➕ 添加新账号</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="accountForm">
                    <input type="hidden" id="editAccountId" value="">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">账号名称 *</label>
                            <input type="text" class="form-control" name="account" id="account" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">密码</label>
                            <div class="input-group">
                                <input type="password" class="form-control" name="password" id="password">
                                <button class="btn btn-outline-secondary" type="button" onclick="toggleEditPassword()">
                                    <i class="bi bi-eye" id="editPasswordToggleIcon"></i>
                                </button>
                            </div>
                            <small class="text-muted">留空表示保持原密码不变</small>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">顺序</label>
                            <input type="number" class="form-control" name="order" id="order" min="0" value="0">
                            <small class="text-muted">用于排序，数字越小越靠前</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">账号类型 *</label>
                            <select class="form-select" name="account_type" id="account_type" required></select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">密保类型</label>
                            <select class="form-select" name="password_type" id="password_type"></select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">状态 *</label>
                            <select class="form-select" name="status" id="status" required></select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">角色个数</label>
                            <input type="number" class="form-control" name="role_count" id="role_count" min="0" value="0">
                            <small class="text-muted">添加/删除角色时会自动更新</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">点卡到期时间</label>
                            <input type="date" class="form-control" name="point_card_expire" id="point_card_expire">
                        </div>
                        <div class="col-12 mb-3">
                            <label class="form-label">备注</label>
                            <textarea class="form-control" name="remarks" id="remarks" rows="2"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveAccount()">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let configData = {};
let currentEditId = null;
let currentPage = 1;
let perPage = 20;
let sortField = 'order';
let sortOrder = 'asc';

$(document).ready(function() {
    loadConfig();
    loadAccounts();
});

// 加载配置
async function loadConfig() {
    try {
        const data = await apiRequest('/api/config');
        configData = data.data;
        
        // 填充账号类型选项
        let typeOptions = '<option value="">请选择</option>';
        configData.account_types.forEach(type => {
            typeOptions += `<option value="${type}">${type}</option>`;
        });
        $('#account_type, #filterType').html(typeOptions);
        $('#filterType').prepend('<option value="">全部类型</option>');
        
        // 填充状态选项
        let statusOptions = '<option value="">请选择</option>';
        configData.account_status.forEach(status => {
            statusOptions += `<option value="${status}">${status}</option>`;
        });
        $('#status, #filterStatus').html(statusOptions);
        $('#filterStatus').prepend('<option value="">全部状态</option>');
        $('#status').val('正常'); // 默认选中正常
        
        // 填充密保类型选项
        let passwordTypeOptions = '<option value="">请选择</option>';
        configData.password_types.forEach(type => {
            passwordTypeOptions += `<option value="${type}">${type}</option>`;
        });
        $('#password_type').html(passwordTypeOptions);
        
        // 填充密保类型筛选下拉
        let filterPasswordTypeOptions = '<option value="">全部密保</option>';
        configData.password_types.forEach(type => {
            filterPasswordTypeOptions += `<option value="${type}">${type}</option>`;
        });
        $('#filterPasswordType').html(filterPasswordTypeOptions);
        
    } catch (error) {
        console.error('加载配置失败:', error);
    }
}

// 加载账号列表
async function loadAccounts() {
    try {
        // 获取所有查询条件
        const searchAccount = $('#searchAccount').val().trim();
        const searchPassword = $('#searchPassword').val().trim();
        const filterType = $('#filterType').val();
        const filterPasswordType = $('#filterPasswordType').val();
        const filterStatus = $('#filterStatus').val();
        const searchOrderMin = $('#searchOrderMin').val().trim();
        const searchOrderMax = $('#searchOrderMax').val().trim();
        const searchRoleCountMin = $('#searchRoleCountMin').val().trim();
        const searchRoleCountMax = $('#searchRoleCountMax').val().trim();
        const searchRemarks = $('#searchRemarks').val().trim();
        
        // 构建查询参数
        const params = new URLSearchParams({
            page: currentPage,
            per_page: perPage,
            sort_field: sortField,
            sort_order: sortOrder
        });
        
        // 添加查询条件
        if (searchAccount) params.append('account', searchAccount);
        if (searchPassword) params.append('password', searchPassword);
        if (filterType) params.append('account_type', filterType);
        if (filterPasswordType) params.append('password_type', filterPasswordType);
        if (filterStatus) params.append('status', filterStatus);
        if (searchOrderMin) params.append('order_min', searchOrderMin);
        if (searchOrderMax) params.append('order_max', searchOrderMax);
        if (searchRoleCountMin) params.append('role_count_min', searchRoleCountMin);
        if (searchRoleCountMax) params.append('role_count_max', searchRoleCountMax);
        if (searchRemarks) params.append('remarks', searchRemarks);
        
        const data = await apiRequest(`/api/accounts?${params.toString()}`);
        const accounts = data.data;
        
        if (accounts.length === 0) {
            $('#accountTableBody').html(`
                <tr>
                    <td colspan="11" class="text-center py-4">
                        <div class="empty-state">
                            <i class="bi bi-inbox"></i>
                            <p>没有找到匹配的账号</p>
                        </div>
                    </td>
                </tr>
            `);
            return;
        }
        
        let html = '';
        accounts.forEach(account => {
            const statusBadge = getStatusBadge(account.status);
            const typeBadge = `<span class="badge bg-info">${account.account_type || '-'}</span>`;
            const passwordHtml = account.password ? 
                `<span class="password-field" data-password="${escapeHtml(account.password)}">
                    <span class="password-hidden">******</span>
                    <i class="bi bi-eye password-toggle" onclick="togglePassword(this)" style="cursor:pointer; margin-left:5px;" title="点击查看密码"></i>
                </span>` : 
                `<span class="text-muted">未设置</span>`;
            
            const expireDisplay = account.point_card_expire || '<span class="badge bg-success">永久</span>';
            const remarksDisplay = account.remarks ? 
                `<span title="${escapeHtml(account.remarks)}">${escapeHtml(account.remarks.substring(0, 15))}${account.remarks.length > 15 ? '...' : ''}</span>` : 
                '<span class="text-muted">-</span>';
            
            html += `
                <tr data-id="${account.id}">
                    <td><strong>${account.order || 0}</strong></td>
                    <td><strong>${account.account}</strong></td>
                    <td>${passwordHtml}</td>
                    <td class="d-none d-md-table-cell">${typeBadge}</td>
                    <td class="d-none d-lg-table-cell">${account.password_type || '-'}</td>
                    <td>${statusBadge}</td>
                    <td class="d-none d-lg-table-cell">${expireDisplay}</td>
                    <td>${account.role_count}个</td>
                    <td class="d-none d-xl-table-cell">${remarksDisplay}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="editAccount('${account.id}')">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteAccount('${account.id}')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        $('#accountTableBody').html(html);
        
        // 显示分页信息
        if (data.total > perPage) {
            console.log(`显示第 ${currentPage} 页，共 ${data.pages} 页，总计 ${data.total} 条记录`);
        }
    } catch (error) {
        console.error('加载账号列表失败:', error);
    }
}

// HTML转义函数
function escapeHtml(text) {
    if (!text) return '';
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, m => map[m]);
}

// 切换列表中密码显示/隐藏
function togglePassword(icon) {
    const passwordField = $(icon).parent();
    const password = passwordField.data('password');
    const hiddenSpan = passwordField.find('.password-hidden');
    
    if ($(icon).hasClass('bi-eye')) {
        // 显示密码
        hiddenSpan.text(password);
        $(icon).removeClass('bi-eye').addClass('bi-eye-slash');
        $(icon).attr('title', '点击隐藏密码');
    } else {
        // 隐藏密码
        hiddenSpan.text('******');
        $(icon).removeClass('bi-eye-slash').addClass('bi-eye');
        $(icon).attr('title', '点击查看密码');
    }
}

// 切换编辑表单中密码显示/隐藏
function toggleEditPassword() {
    const passwordInput = $('#password');
    const icon = $('#editPasswordToggleIcon');
    
    if (passwordInput.attr('type') === 'password') {
        passwordInput.attr('type', 'text');
        icon.removeClass('bi-eye').addClass('bi-eye-slash');
    } else {
        passwordInput.attr('type', 'password');
        icon.removeClass('bi-eye-slash').addClass('bi-eye');
    }
}

// 编辑账号
async function editAccount(id) {
    try {
        // 从表格中获取账号数据
        const accounts = await apiRequest('/api/accounts');
        const account = accounts.data.find(a => a.id === id);
        
        if (!account) {
            showNotification('账号不存在', 'error');
            return;
        }
        
        // 填充表单
        $('#editAccountId').val(account.id);
        $('#account').val(account.account);
        $('#password').val(account.password || ''); // 密码回显，可以查看和修改
        $('#password').attr('placeholder', account.password ? '留空则不修改密码' : '请输入密码');
        $('#order').val(account.order || 0);
        $('#account_type').val(account.account_type);
        $('#password_type').val(account.password_type || '');
        $('#status').val(account.status);
        $('#role_count').val(account.role_count || 0);
        $('#point_card_expire').val(account.point_card_expire || '');
        $('#remarks').val(account.remarks || '');
        
        // 修改模态框标题
        $('#modalTitle').text('✏️ 编辑账号');
        currentEditId = id;
        
        // 显示模态框
        new bootstrap.Modal(document.getElementById('addAccountModal')).show();
    } catch (error) {
        console.error('加载账号数据失败:', error);
    }
}

// 保存账号
async function saveAccount() {
    const form = document.getElementById('accountForm');
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const formData = new FormData(form);
    const data = Object.fromEntries(formData);
    const editId = $('#editAccountId').val();
    
    try {
        if (editId) {
            // 更新
            await apiRequest(`/api/accounts/${editId}`, {
                method: 'PUT',
                body: JSON.stringify(data)
            });
            showNotification('账号更新成功');
        } else {
            // 新增
            await apiRequest('/api/accounts', {
                method: 'POST',
                body: JSON.stringify(data)
            });
            showNotification('账号添加成功');
        }
        
        bootstrap.Modal.getInstance(document.getElementById('addAccountModal')).hide();
        form.reset();
        $('#editAccountId').val('');
        currentEditId = null;
        loadAccounts();
    } catch (error) {
        console.error('保存账号失败:', error);
    }
}

// 删除账号
async function deleteAccount(id) {
    if (!confirm('确定要删除这个账号吗？此操作将同时删除该账号下的所有角色和任务记录。')) {
        return;
    }
    
    try {
        await apiRequest(`/api/accounts/${id}`, { method: 'DELETE' });
        showNotification('账号删除成功');
        loadAccounts();
    } catch (error) {
        console.error('删除账号失败:', error);
    }
}

// 导出Excel
function exportToExcel() {
    window.location.href = '/api/accounts/export';
    showNotification('正在导出Excel文件...');
}

// 下载导入模板
function downloadTemplate() {
    // 创建模板数据
    const template = [
        ['账号', '密码', '账号类型', '密保类型', '状态', '角色个数', '点卡到期', '备注'],
        ['示例账号1', 'password123', '主号', '实体将军令', '正常', '3', '2025-12-31', '这是示例数据'],
        ['示例账号2', 'password456', '小号', '手机将军令', '正常', '1', '', '点卡到期留空表示永久'],
        ['', '', '', '', '', '', '', '']
    ];
    
    // 创建工作表
    const ws = XLSX.utils.aoa_to_sheet(template);
    
    // 设置列宽
    ws['!cols'] = [
        {wch: 15}, // 账号
        {wch: 15}, // 密码
        {wch: 12}, // 账号类型
        {wch: 12}, // 密保类型
        {wch: 10}, // 状态
        {wch: 10}, // 角色个数
        {wch: 12}, // 点卡到期
        {wch: 30}  // 备注
    ];
    
    // 创建工作簿
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '账号导入模板');
    
    // 下载
    XLSX.writeFile(wb, '账号导入模板.xlsx');
    showNotification('模板下载成功');
}

// 处理文件导入
async function handleFileImport(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    // 验证文件类型
    if (!file.name.match(/\.(xlsx|xls)$/)) {
        showNotification('请选择Excel文件（.xlsx或.xls）', 'error');
        event.target.value = '';
        return;
    }
    
    // 验证文件大小（最大5MB）
    if (file.size > 5 * 1024 * 1024) {
        showNotification('文件大小不能超过5MB', 'error');
        event.target.value = '';
        return;
    }
    
    // 显示加载提示
    showNotification('正在导入，请稍候...', 'info');
    
    // 创建FormData
    const formData = new FormData();
    formData.append('file', file);
    
    try {
        const response = await fetch('/api/accounts/import', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.code === 200) {
            const data = result.data;
            let message = `导入完成！成功: ${data.success_count}条`;
            
            if (data.error_count > 0) {
                message += `，失败: ${data.error_count}条`;
                if (data.errors && data.errors.length > 0) {
                    message += '\n错误信息:\n' + data.errors.join('\n');
                }
            }
            
            showNotification(message, data.error_count > 0 ? 'warning' : 'success');
            loadAccounts(); // 刷新列表
        } else {
            showNotification(result.message || '导入失败', 'error');
        }
    } catch (error) {
        showNotification('导入失败: ' + error.message, 'error');
    }
    
    // 清空文件选择
    event.target.value = '';
}

// 状态徽章
function getStatusBadge(status) {
    const badges = {
        '正常': 'bg-success',
        '异常': 'bg-warning',
        '作废': 'bg-secondary',
        '过期': 'bg-danger',
        '封禁': 'bg-dark'
    };
    return `<span class="badge ${badges[status] || 'bg-secondary'}">${status}</span>`;
}

// 重置搜索
function resetSearch() {
    $('#searchAccount').val('');
    $('#searchPassword').val('');
    $('#filterType').val('');
    $('#filterPasswordType').val('');
    $('#filterStatus').val('');
    $('#searchOrderMin').val('');
    $('#searchOrderMax').val('');
    $('#searchRoleCountMin').val('');
    $('#searchRoleCountMax').val('');
    $('#searchRemarks').val('');
    currentPage = 1;
    loadAccounts();
}

// 回车搜索
$('#searchAccount').on('keypress', function(e) {
    if (e.key === 'Enter') {
        loadAccounts();
    }
});

// 回车搜索 - 绑定所有输入框
$('#searchAccount, #searchPassword, #searchOrderMin, #searchOrderMax, #searchRoleCountMin, #searchRoleCountMax, #searchRemarks').on('keypress', function(e) {
    if (e.key === 'Enter') {
        loadAccounts();
    }
});

// 下拉框改变时自动搜索
$('#filterType, #filterPasswordType, #filterStatus').on('change', function() {
    loadAccounts();
});

// 模态框关闭时重置表单
$('#addAccountModal').on('hidden.bs.modal', function () {
    $('#accountForm')[0].reset();
    $('#editAccountId').val('');
    $('#modalTitle').text('➕ 添加新账号');
    $('#password').attr('placeholder', '请输入密码');
    currentEditId = null;
});

// 排序表格
function sortTable(field) {
    if (sortField === field) {
        // 同一字段切换升序/降序
        sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
    } else {
        // 新字段默认升序
        sortField = field;
        sortOrder = 'asc';
    }
    currentPage = 1;
    loadAccounts();
}

// 重置排序
async function resetOrder() {
    if (!confirm('确定要重置排序吗？这将根据账号表的order字段，联动更新角色管理和任务中心的order字段。')) {
        return;
    }
    
    try {
        const data = await apiRequest('/api/accounts/reset-order', {
            method: 'POST'
        });
        showNotification(data.message);
        loadAccounts();
    } catch (error) {
        console.error('重置排序失败:', error);
    }
}
</script>
{% endblock %}
